<template>
    <div class="frame withdraw">
            <el-dialog
            :title="this.$t('dt.rechargeTitle')"
            :visible.sync="show"
            width="440px"
            :before-close="closeFrame"
            >  
            <div  v-if="!ifpassword"  class="content ">
                <div class="content-title">{{unit}}{{$t("dt.balanceRecharge")}}</div>
                <div class="content-copy">
                <span>{{datxDetail.name}}</span>
                <img src="../../assets/images/copy.png" alt=""
                          v-clipboard:copy="datxDetail.name"
                          v-clipboard:success="onCopy"
                          v-clipboard:error="onError">
               </div>
                <div class="content-notice">
                    <span>{{$t("dt.rechargeNotice1")}}{{$t("dt.rechargeNotice2")}}{{coinName}},{{$t("dt.rechargeNotice2")}}</span>
                </div>
                <div v-if="unit=='DEOS'">
                    <div  class="content-input">
                        <div class="sub ">
                            <div class="sub-lable">{{$t("dt.rechargeAddress")}}</div>
                            <div class="sub-input flex">
                                <div>
                                  <input v-model="deosAdress" type="text" placeholder=""  disabled class="disabled">
                                  <p style="  font-size: 12px;color: #98889b; padding: 5px 0">{{$t("dt.memoNotice")}}</p>
                                </div>
                                <div style="flex:1"></div>
                                <div>
                                    <img src="../../assets/images/copy.png" alt=""
                                    v-clipboard:copy="deosAdress"
                                    v-clipboard:success="onCopy"
                                    v-clipboard:error="onError">
                                </div>
                            </div>

                        </div>
                        <div class="sub ">
                            <div class="sub-lable">{{$t("dt.memo")}}</div>
                            <div class="sub-input flex">
                                <input v-model="datxDetail.name" type="text" placeholder="" disabled class="disabled">
                                <div style="flex:1"></div>
                              <div>
                                <img src="../../assets/images/copy.png" alt=""
                                     v-clipboard:copy="datxDetail.name"
                                     v-clipboard:success="onCopy"
                                     v-clipboard:error="onError">
                              </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-if="unit=='DETH'">
                    <div  class="content-input">
                            <div class="sub ">
                                <div class="sub-lable">您正向DATx链上的ETH托管账户充值(最少充值0.5ETH)：</div>
                                <div class="sub-input flex">
                                    <input type="text" placeholder="请输入您的充值金额" v-model="amount">
                                    <div style="flex:1"></div>
                                    <div>ETH</div>                
                                </div>
                            </div>
                            <div class="sub ">
                                <div class="sub-lable">充值成功后，您将获得</div>
                                <div class="sub-input flex">
                                    <input class="disabled" disabled type="text" placeholder="金额与您充值的ETH相同" :value=amount-amount/200>
                                    <div style="flex:1"></div>
                                    <div>dETH</div>
                                </div>
                            </div>
                    </div>
                    <div class="content-input" >
                            <div class="sub" style="border:none;padding-bottom: 0px;  margin-bottom: 5px;">
                                <div class="sub-lable">{{$t("dt.chanceWallet")}}</div>
                                <div class="sub-detail ">
                                    <ul>
                                        <li class="flex" v-for="(item,index) of tableData" :key="index" @click="chanceWallet(index)" :class="{coindetil:stateChance==index}">
                                                <img class="coinpic" src="../../assets/images/coineth.png" alt="">
                                                <div class="coindetail">
                                                    <div>
                                                        <span>ETH-Wallet {{index+1}}</span>
                                                        <span>{{$t("dt.balance")}}：{{item.balance|tofix}} ETH</span>
                                                    </div>
                                                    <div>
                                                        {{item.address}}
                                                    </div>
                                                </div>
                                                <div style="flex: 1"></div>
                                                <div class="coinconfirm" :class="{coinconfirm2:stateChance==index}"></div>
                                        </li>
                                    </ul>                                      
                                </div>
                            </div>
                    </div>
                 </div>
                <div v-if="unit=='DBTC'">
                    <div  class="content-input">
                        <div class="sub " style="border:none;">
                            <div class="sub-lable">{{$t("dt.rechargeAddress")}}</div>
                            <div class="sub-input flex">
                                <input type="text"  v-model="btcAdress" disabled class="disabled">
                                <div style="flex:1"></div>
                                <div>
                                    <img src="../../assets/images/copy.png" alt=""
                                    v-clipboard:copy="btcAdress"
                                    v-clipboard:success="onCopy"
                                    v-clipboard:error="onError">
                                </div>
                            </div>
                        </div>
                    
                    </div>
                </div>
                <div class="content-button">
                    <button @click="confirm">{{$t("dt.recharge")}}</button>
                </div>
            </div>
            <div v-else class="password">
              <p>{{$t("dt.password")}}</p>
              <input type="password"  :placeholder="this.$t('dt.passwordPlaceholder')" v-model="secret">
              <button @click="passwordconfirm">{{$t("dt.submiit")}}</button>
            </div>
        </el-dialog>
        <el-dialog
          title="注意"
          :visible.sync="showtext"
          width="440px"
          :before-close="closeFrame">
          <div class="notice ">
            <p v-if="unit=='DBTC'">{{$t("dt.reText1")}}</p>
            <p v-if="unit=='DETH'" >{{$t("dt.reText2")}}</p>
            <p v-if="unit=='DEOS'">{{$t("dt.reText3")}}</p>
          </div>

        </el-dialog>
        </div>
</template>
<script>
  import {getBtcAddress,addBtcAddress} from '../../api/serverApi'
  import {rechargeDatx} from '../../api/chainApi'
  import {getAllOuterAccount,bindAddress,selectOuterDatx} from '../../service/datxService'
  import {sendTrx,getBalance,selectOuterETH} from '../../service/ethService'
  import {getPrice,validateSecret,getforNumber} from '../../utils/commonUtils'

  import Async from 'async'

  export default{
    data(){
        return{
            ifpassword:false,
             show:true,
             showtext:false,
             tableData:{
               balance:'',//ETH余额
               address:''//地址
             }, //ETH钱包信息
             datxDetail:{},
            //  unit:"DBTC",
             stateChance:null,
            deosAdress:'datxtest1112',
            btcAdress:'',
            addressEth:'',//ETH地址
            balanceEth:0,
            secret:"",
            amount:0.5,
            gasprice:0,
            gaslimit:35000,
            ishash:false

        }
    },
    filters:{
     tofix: function(value){
       return  Number(value).toFixed(4)
     }
    },
   props: ["unit"],
   created(){
      this.datxDetail = JSON.parse(window.sessionStorage.getItem("walletdetail"));
      this.getAdresss();
      if( this.unit=='DBTC'){
        this.coinName="BTC"
      }
      else if(this.unit=='DETH'){
        this.coinName="ETH"
      }
      else if(this.unit=='DEOS'){
        this.coinName="EOS"
      }
  },

   methods:{
       // 获取ETH钱包
       getAllout() {
         let self = this;
         let obj = getAllOuterAccount();
         if (obj == null) {
           this.istable = false;
         } else {
           this.tableData = obj
         }
         let table = [];
         Async.each(this.tableData, function (obj, callback) {
           obj.value = '';
           obj.balance = '';
           Async.series({
             balance: function (callback) {
               getBalance(obj.address, function (err, res) {
                 callback(err, res)
               })
             },
             value: function (callback) {
               getPrice(function (err, res) {
                 callback(err, res)
               })
             }
           }, function (err, result) {
             obj.balance = result.balance;
             obj.value = parseFloat(result.balance) * parseFloat(result.value.USD);
             table.push(obj);
             callback(null, null)
           })
         }, function (err) {
           if (err)
             console.log(err);
           self.tableData = table;
         })
       },
        // 转入
        closeFrame(){
           this.$emit('rechargeListen',false)
        },
        // 复制成功
        onCopy(){
            this.$message({
                message:this.$t("dt.copySuccess"),
                type: 'success'
                });
        },

        // 复制失败
        onError(){
            this.$message({
              message:this.$t("dt.copydefault"),
                type: 'erro'
                });
        },

        // 选择地址
        chanceWallet(val){
            this.stateChance=val;
            this.addressEth=this.tableData[val].address
            this.balanceEth=this.tableData[val].balance
            console.log(val,this.addressEth,this.balanceEth)
        },
       // 获取货币下地址
     getAdresss(){
          if(this.unit=='DBTC'){
            let creds="userId="+this.datxDetail.name+"&coinName="+"BTC"
              getBtcAddress(creds).then(res=>{
                if(res.code==200&&res.message=="OK"){
                  this.btcAdress=res.data
                }else {
                  addBtcAddress(creds).then(res=>{
                    if(res.code==200){
                      this.btcAdress=res.data
                    }else {
                      this.$message.error(this.$("dt.noCreatRechargeAdress"))
                    }
                  })
                }
              })
          }
          else if(this.unit=='DETH'){
            this.getAllout();
            this.stateChance=null;
            console.log(this.tableData)
            // this.addressEth=this.tableData[0].address;
            // this.balanceEth=this.tableData[0].balance;
            // console.log(this.tableData,this.addressEth,this.balanceEth)
            // this.gasprice=this.amount/(200*0.00000002)*Math.pow(10,9);
            this.gasprice=5*Math.pow(10,9);
          }else {

          }
     },
     confirm(){
          if(this.unit=='DBTC'){
             rechargeDatx("GET","BTC",this.datxDetail.name,this.btcAdress).then(res =>{
               if(res.code==200&&res.message=="OK"){
                  if(res.data.hash){
                    this.show=false;
                    this.showtext=true;
                  }else {
                    this.ifpassword=true
                  }
               }else {
                 this.$message.error(res.message)
               }
             })
          }else if(this.unit=='DETH'){
            if(this.addressEth==""){
               // this.$message.error("最少充值0.5ETH,请查看钱包余额和充值数量")
              this.$message.error("请选择钱包")
            }else {
              rechargeDatx("GET","ETH",this.datxDetail.name,this.addressEth).then(res =>{
                if(res.code==200&&res.message=="OK"){
                  console.log(res.data.hash)
                  // this.ishash=false;
                  if(res.data.hash){
                    this.ishash=true;
                  }else {
                    this.ishash=false;
                  }
                  this.ifpassword=true
                }else {
                  this.$message.error(res.message)
                }
              })
            }
          }else {
            this.show=false;
            this.showtext=true;
          }
        },

      passwordconfirm(){
       if(validateSecret(this.secret)){
           switch(this.unit){
             case "DBTC":
               let obj=selectOuterDatx(this.datxDetail.name,this.secret)
               let privateKey=obj.privateKey
               if(privateKey){
                 console.log(this.datxDetail.name,this.btcAdress,privateKey)
                 bindAddress(this.datxDetail.name,this.btcAdress,privateKey,(erro,data) =>{
                   console.log(erro,data)
                   if (!erro){
                     rechargeDatx("SET","BTC",this.datxDetail.name,this.btcAdress).then(res =>{
                       if(res.code==200){
                         this.$message.success("映射成功")
                       }else {
                         this.$message.error(res.message)
                       }
                     })
                     this.show=false;
                     this.showtext=true;
                   } else {
                     this.$message.error("绑定地址失败")
                   }
                 });
               }else {
                 this.$message.error("私钥不存在")
               }
               break;

             case "DETH":
               if(this.ishash==false){
                 let obj=selectOuterDatx(this.datxDetail.name,this.secret);
                 let privateKey=obj.privateKey;
                 if(privateKey){
                   console.log(this.datxDetail.name,this.addressEth.toLowerCase(),privateKey,)
                   bindAddress(this.datxDetail.name,this.addressEth.toLowerCase(),privateKey,(erro,data) =>{
                     console.log(erro,data)
                     if (!erro){
                       rechargeDatx("SET","ETH",this.datxDetail.name,this.addressEth).then(res =>{
                         if(res.code==200&&res.data.hash){
                           this.$message.success("映射成功")
                         }else {
                           this.$message.error("映射失败")
                         }
                       })
                       let address='0xDaBBbacFF575a85E47EA1D1ff97f55B22Ab3184A'
                       console.log(this.addressEth, address.toLowerCase(),this.secret, this.amount,this.gasprice,this.gaslimit,'ETH',)
                       sendTrx(this.addressEth, address.toLowerCase(),this.secret, this.amount,this.gasprice,this.gaslimit,'ETH', (erro,data)=>{
                         console.log(erro,data)
                         if(!erro){
                           this.$message.success("充值成功")
                           this.show=false;
                           this.showtext=true;
                         }else {
                           this.$message.error("充值失败");
                           this.$emit('rechargeListen',false)
                         }
                       });
                       this.show=false;
                       this.showtext=true;
                     } else {
                       this.$message.error("绑定地址失败")
                     }
                   });
                 }else {
                   this.$message.error("私钥不存在")
                 }

               }else {
                 let address='0xDaBBbacFF575a85E47EA1D1ff97f55B22Ab3184A'
                 console.log(this.addressEth, address.toLowerCase(), this.secret, this.amount,this.gasprice,this.gaslimit,'ETH',)
                 sendTrx(this.addressEth, address.toLowerCase(), this.secret, this.amount,this.gasprice,this.gaslimit,'ETH', (erro,data)=>{
                   console.log(erro,data)
                   if(!erro){
                     this.$message.success("充值成功")
                     this.show=false;
                     this.showtext=true;
                   }else {
                     this.$message.error("充值失败");
                     this.show=false;
                     this.showtext=true;
                   }
                 });
               }
               break;

             case "DEOS":
               this.show=false;
               this.showtext=true;
               break;

             default:
               this.$message.error("币种不存在")

           }

       }else{
         this.$message.error('密码错误');
         this.$emit('rechargeListen',false)
       }
     }
    } 
}
 
</script>
<style lang="less" scoped>
.withdraw{
    .flex{
        display: flex;
    }
    .content{
        .content-title{
            text-align: center;
            color: #98889b;
            font-size: 18px;
        }
        .content-copy{
            font-size: 12px;
            color: #666666;
            text-align: center;    
            img{
                width:12px;
                height:14px;
                margin-bottom: -3px;
                cursor: pointer;
            }
        }
        .content-notice{
            font-size: 12px;
            color: #98889b;
            padding: 20px 20px 0;
        }
        .content-input{
            padding: 10px 20px;
            margin-top: 20px;
            background:#fbfbfc;; 
            color: #666666;
            .sub{
                padding-bottom: 20px;
                margin-bottom: 10px; 
                border-bottom: 1px solid #eaedf5;
              &-lable{
                margin-bottom: 15px;
              }
              &-input{
                  line-height: 34px;
                  img{
                      width: 16px;
                      height: 19px;
                      margin-bottom: -4px;
                      margin-right: 8px;
                      cursor: pointer;
                  }
              }
              &-detail{
                  ul{ 
                      li{
                          background: #fff;
                          list-style: none;
                          margin-bottom: 10px;
                          padding: 5px 0;
                          border: solid 1px #f7f7f8;
                          border-radius: 4px;
                          cursor: pointer;
                          .coinpic{
                              width:30px;
                              height: 30px; 
                              margin: 10px 5px;
                          }
                          .coindetail{
                              /*padding: 0 10px;*/
                             color: #666666;
                             font-size: 12px;
                             line-height: 30px;
                             span{
                               color: #000000;
                               padding-right: 30px;
                             }
                          }
                          .coinconfirm{
                                  width: 25px;
                                  height: 25px;
                                  margin: 15px 8px 15px 0;
                                  background-image: url( ../../assets/images/select-2.png);
                                  background-repeat: no-repeat;
                                  background-size: 100%;
                          }
                          .coinconfirm2{
                                   width: 25px;
                                   height: 25px;
                                   margin: 15px 8px 15px 0;
                                   background-image: url( ../../assets/images/select-1.png);
                                   background-repeat: no-repeat;
                                   background-size: 100%;
                          }
                      }
                      .coindetil{
                           border: solid 1px #98889b;
                           box-shadow: 0 0 4px 0 rgba(152, 136, 155, 0.44);
                      }
                      li:hover{
                        border: solid 1px #98889b;
                      }
                  }
              }
            }
            input{
            width: 349px;
            height: 34px;
            display: block;
            padding: 0 10px;
            border-radius: 4px;
            border: solid 1px #eeeeee;
            background-color: #ffffff; 
            }
          .disabled{
            background-color: #f5f7fa;
            border-color: #e4e7ed;
            color: #c0c4cc;
            cursor: not-allowed;
          }
            input::-webkit-input-placeholder {
            font-size: 12px;
            color: #c5c7cb;   
            }
         
         
        }
        .content-button{ 
            margin: 22px 0;
            button{
                color:#fff;
                width: 400px;
                margin:  0 auto;
                display: block;
                border-radius: 4px;
                line-height:32px;
                text-align: center;
                background-color: #98889b;
                outline: none;
                border: none;
                cursor: pointer;
            }
            button:hover{
                opacity: .8;
            }   
        }
    }
    .notice{
      margin: 20px;
      min-height: 150px;
      p{
       font-size: 16px;
      }
    }
    .password{
    padding: 0 20px;
    p{
      color: #666666;
      padding:15px 0;
    }
    input{
      width: 100%;
      height: 34px;
      padding: 0 10px;
      border-radius: 4px;
      border: solid 1px #eeeeee;
      background-color: #ffffff;
    }
    input::-webkit-input-placeholder {
      font-size: 12px;
      color: #c5c7cb;
    }
    button{
      width: 100%;
      margin: 30px 0 10px;
      color: #fff;
      border-radius: 4px;
      text-align: center;
      line-height: 40px;
      background: #98889b;
      outline: none;
      cursor: pointer;
    }
    button:hover{
      opacity: .8;
    }
  }

}
</style>
<style lang="less" >
.frame{
    .el-dialog__wrapper{ 
        .el-dialog{
                    border-radius: 8px;
            }
            .el-dialog__header{
                border-bottom:1px solid #eaedf5;
                color:#000000;
                font-size: 18px;
                font-weight: bold;
                padding:20px;
            }
            .el-dialog__body{
                padding:30px 0;
            }
            .el-dialog__headerbtn .el-dialog__close{
                color: #666666;
                
        }
    }          
}
</style>

